<template>
  <!-- 源代码 -->
  <div>
    <!-- 气泡框 -->
    <div v-if="showBubble" class="speech-bubble" :style="bubbleStyle">
      <div class="bubble-text">{{ bubbleText }}</div>
      <div class="bubble-tail"></div>
    </div>

    <!-- 宠物容器 -->
    <div
      class="pet-container"
      ref="petElement"
      @mousedown="handlePetMoveStart"
      @mousemove="handlePetMove"
      @mouseup="handlePetMoveEnd"
      v-if="petVisible"
    >
      <div style="position:relative">
        <img
          :src="currentGifSrc"
          class="pet-gif"
          :style="{ width: `${petSize}px` }"
          @mousemove="handleMouseMove"
          @mouseleave="handleMouseLeave"
          @click="toggleChat"
        />
      </div>
    </div>

    <!-- 聊天窗口组件，画红线不代表有错 -->
    <ChatWindow v-model:visible="chatVisible" />

    <!-- 情感化弹窗 -->
    <transition name="fade" v-if="popupVisible">
      <div class="dialog-container">
        <div class="close-dialog">
          <div class="pet-emoji-container">
            <img src="@\assets\cute_pet\萌鼠嘟嘟\情绪\叹气.gif" alt style="width: 100%;height: 100%;" />
          </div>

          <div class="dialog-text">
            <p v-if="popupContentV" class="text-jitter">呜呜...主人不要丢下我嘛 QAQ</p>

            <div v-if="!popupContentV" class="hint-text">
              <span class="heart-pulse">❤️</span> 我会乖乖等你回来的～
              <br />想我的时候，随时可以到
              <br />
              <img src class="icon-jiggle" />
              <u style="font-weight:bold;font-size:16px">个人中心</u> 接我回家
            </div>
          </div>

          <div class="action-buttons" v-if="popupContentV">
            <button
              class="cancel-btn"
              @mouseover="hoverButton(true)"
              @mouseleave="hoverButton(false)"
              @click="confirmStay"
            >🐾 再陪我一会</button>
            <button class="confirm-btn" @click="confirmLeave">狠心离开...</button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import {
  ref,
  defineProps,
  onMounted,
  onUnmounted,
  computed,
  nextTick,
  watch
} from "vue";
import ChatWindow from "@/views/components/ChatWindow.vue";
import axios from "@/utils/request";

// 接收父组件传递的属性
const props = defineProps({
  bubbleText: {
    type: String,
    default: ""
  },
  showBubble: {
    type: Boolean,
    default: false
  }
});

/*宠物相关*/
const petVisible = ref(true);
// 聊天窗口
const chatVisible = ref(false);
// 移动
const isMoving = ref(false); // 移动标志
const dragStartX = ref(0);
const dragStartY = ref(0);
const petStartX = ref(0);
const petStartY = ref(0);
const dragDistance = ref(0); // 拖动距离
const DRAG_THRESHOLD = 5; // 拖动阈值
// 缩放
const isMiddleButtonPressed = ref(false);
// 关闭弹窗
const popupVisible = ref(false);
const popupContentV = ref(true);

/* 宠物---宠物默认位置 */
const resetPetPosition = () => {
  // 获取窗口宽度和高度
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;

  // 获取宠物元素的宽度和高度
  const petWidth = petElement.value.offsetWidth;
  const petHeight = petElement.value.offsetHeight;

  // 计算右下角的位置
  const newLeft = windowWidth - petWidth - 160;
  const newTop = windowHeight - petHeight - 140;

  // 设置宠物的位置
  petElement.value.style.left = `${newLeft}px`;
  petElement.value.style.top = `${newTop}px`;
};

/* 宠物---聊天窗口：点击宠物，打开聊天窗口 */
const toggleChat = () => {
  // 只有当拖动距离小于阈值且不是正在移动时，才切换聊天窗口
  if (
    dragDistance.value < DRAG_THRESHOLD &&
    !isMoving.value &&
    !popupVisible.value
  ) {
    chatVisible.value = !chatVisible.value;
  }
  // 重置拖动距离
  dragDistance.value = 0;
};

/* 宠物---移动位置：长按左键，移动鼠标使宠物移动（鼠标按下，鼠标移动，鼠标松开） */
const handlePetMoveStart = event => {
  event.preventDefault(); // 阻止默认的拖放行为
  if (event.button === 0) {
    // 左键
    dragStartX.value = event.clientX;
    dragStartY.value = event.clientY;
    console.log("鼠标" + dragStartX.value + dragStartY.value);
    petStartX.value = petElement.value.offsetLeft;
    petStartY.value = petElement.value.offsetTop;
    console.log("宠物" + petStartX.value + petStartY.value);
    isMoving.value = true;
  } else if (event.button === 1) {
    // 中键
    isMiddleButtonPressed.value = true;
  }
};
const handlePetMove = event => {
  if (isMoving.value) {
    const dx = event.clientX - dragStartX.value;
    const dy = event.clientY - dragStartY.value;
    // 计算拖动距离
    dragDistance.value = Math.sqrt(dx * dx + dy * dy);

    // 获取窗口和宠物元素的宽度和高度
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const petWidth = petElement.value.offsetWidth;
    const petHeight = petElement.value.offsetHeight;

    // 计算新的位置
    let newLeft = petStartX.value + dx;
    let newTop = petStartY.value + dy;

    // 判断是否在右下方1/3区域
    const isInExitZone = newTop > windowHeight * 0.66;

    // 特殊区域处理
    if (isInExitZone) {
      // 允许向右拖出窗口
      newLeft = Math.max(0, Math.min(newLeft, windowWidth));
      // 保持垂直方向限制
      newTop = Math.max(0, Math.min(newTop, windowHeight - petHeight));
    } else {
      // 常规区域限制
      newLeft = Math.max(0, Math.min(newLeft, windowWidth - petWidth));
      newTop = Math.max(0, Math.min(newTop, windowHeight - petHeight));
    }

    petElement.value.style.left = `${newLeft}px`;
    petElement.value.style.top = `${newTop}px`;

    if (newLeft > windowWidth - (petWidth / 4) * 3) {
      popupVisible.value = true;
      popupContentV.value = true;
    } else {
      popupVisible.value = false;
      popupContentV.value = false;
    }
  }
};
const handlePetMoveEnd = () => {
  isMoving.value = false;
  isMiddleButtonPressed.value = false;
};
/* 宠物---调整大小：中键上下滑动 */
const handleMouseWheel = event => {
  if (isMiddleButtonPressed.value) {
    const delta = event.deltaY;
    if (delta > 0) {
      // 向下滚动，缩小宠物
      petSize.value = Math.max(petSize.value - 10, 50);
    } else {
      // 向上滚动，放大宠物
      petSize.value = Math.min(petSize.value + 10, 250);
    }
  }
};
/* 宠物---关闭宠物 */
const confirmStay = () => {
  popupVisible.value = false;
  resetPetPosition();
};
const confirmLeave = () => {
  popupContentV.value = false;
  setTimeout(() => {
    popupVisible.value = false;
    petVisible.value = false;
  }, 3000);
};
const hoverButton = isHovering => {
  if (isHovering) {
    document.querySelector(".cancel-btn").classList.add("hover-animation");
  } else {
    document.querySelector(".cancel-btn").classList.remove("hover-animation");
  }
};

/*  宠物---自身效果 */
const petElement = ref(null);
const bubblePos = ref({ x: 0, y: 0 });
// 批量导入图片，返回一个对象，其中键是匹配的文件路径，值是动态导入函数
const imageImports = import.meta.glob("@/assets/cute_pet/萌鼠嘟嘟/*.gif");
// const imageImports = import.meta.glob("@/assets/cute_pet/社畜小狐狸/*.gif");
const gifSources = ref([]);
const currentGifSrc = ref("");
// 默认图片路径
const defaultGif = ref("");
// 动画是否正在播放的状态
const isAnimating = ref(false);
// 记录上一次鼠标所在的区域
const lastRegion = ref(null);
// 宠物大小
const petSize = ref(120);

// 动态加载图片
Promise.all(Object.values(imageImports).map(importFn => importFn())).then(
  modules => {
    gifSources.value = modules.map(module => module.default);
    // 找到默认图片的路径
    defaultGif.value =
      gifSources.value.find(src => src.includes("default.gif")) || "";
    currentGifSrc.value = defaultGif.value;
  }
);

// 获取宠物元素位置
const updatePosition = () => {
  if (petElement.value) {
    const rect = petElement.value.getBoundingClientRect();
    bubblePos.value = {
      x: rect.left + rect.width / 2,
      y: rect.top - 10 // 上移10
    };
  }
};

// 气泡样式计算
const bubbleStyle = computed(() => ({
  left: `${bubblePos.value.x}px`,
  bottom: `calc(100% - ${bubblePos.value.y}px)`, // 使用 calc 计算底部位置
  transform: "translateX(-50%)" // 水平居中
}));

// 处理鼠标移动通用事件
const handleMouseMoveGeneral = event => {
  if (!isMiddleButtonPressed.value) {
    return;
  }
  // 这里可以添加更多中键按下时的移动处理逻辑
};

// 处理鼠标移动事件
const handleMouseMove = event => {
  // 如果动画正在播放，不做处理
  if (isAnimating.value) return;

  const target = event.target;
  const rect = target.getBoundingClientRect();
  const x = event.clientX - rect.left; // 鼠标相对于图片左上角的 x 坐标
  const y = event.clientY - rect.top; // 鼠标相对于图片左上角的 y 坐标

  const petWidth = rect.width;
  const petHeight = rect.height;

  // 将图片区域分成3x3
  const regionWidth = petWidth / 3;
  const regionHeight = petHeight / 3;

  // 计算当前鼠标所在的区域
  const regionX = Math.floor(x / regionWidth);
  const regionY = Math.floor(y / regionHeight);

  // 生成一个唯一的区域标识符
  const regionId = regionX + regionY * 3;

  // 如果鼠标进入了新的区域
  if (lastRegion.value !== regionId) {
    // 从 gifSources 中随机选择一张图片，且不为当前默认图片
    const availableGifs = gifSources.value.filter(
      src => src !== defaultGif.value
    );
    const randomGif =
      availableGifs[Math.floor(Math.random() * availableGifs.length)];

    if (randomGif) {
      currentGifSrc.value = randomGif;
      isAnimating.value = true;
      lastRegion.value = regionId;

      // 模拟动画播放完成，这里假设动画播放时间为 2 秒，可根据实际情况调整
      setTimeout(() => {
        currentGifSrc.value = defaultGif.value;
        isAnimating.value = false;
        lastRegion.value = null;
      }, 2000);
    }
  } else {
    // 如果不在任何区域，显示默认图片
    currentGifSrc.value = defaultGif.value;
    lastRegion.value = null;
  }
};

// 处理鼠标离开事件
const handleMouseLeave = () => {
  currentGifSrc.value = defaultGif.value;
  isAnimating.value = false;
  lastRegion.value = null;
};

// 监听窗口变化
onMounted(() => {
  nextTick(() => {
    resetPetPosition();
    updatePosition();
  });
  window.addEventListener("resize", updatePosition);
  window.addEventListener("mousemove", handleMouseMoveGeneral);
  window.addEventListener("wheel", handleMouseWheel);
});

onUnmounted(() => {
  window.removeEventListener("resize", updatePosition);
  window.removeEventListener("mousemove", handleMouseMoveGeneral);
  window.removeEventListener("wheel", handleMouseWheel);
});

// 监听 bubbleText 的变化
watch(
  () => props.bubbleText,
  () => {
    nextTick(() => {
      updatePosition();
    });
  }
);

// 监听 showBubble 的变化
watch(
  () => props.showBubble,
  newVal => {
    if (newVal) {
      nextTick(() => {
        updatePosition();
      });
    }
  }
);
</script>

<style scoped>
/* 宠物容器定位 */
.pet-container {
  position: fixed; /* 使内部绝对定位元素相对于此容器 */
  z-index: 9999;
}

/* 宠物样式 */
.pet-gif {
  width: 120px;
  cursor: pointer;
  transition: transform 0.3s;
}

/* 气泡定位调整 */
.speech-bubble {
  position: fixed;
  background: #fff;
  padding: 10px 15px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 300px; /* 增大最大宽度 */
  min-width: 200px;
  word-wrap: break-word;
  z-index: 10000; /* 确保在宠物上方 */
  transform-origin: bottom center;
}

.bubble-text {
  font-size: 12px;
  color: #333;
  letter-spacing: 1px;
}

.bubble-tail {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 10px solid #fff;
}
/* 关闭宠物弹窗 */
.close-dialog {
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10001;
  width: 320px;
  padding: 25px;
  border-radius: 25px;
  background: linear-gradient(135deg, #fff2f8 0%, #e6f9ff 100%);
  box-shadow: 0 8px 32px rgba(255, 182, 193, 0.2);
  border: 2px solid #ffd1dc;
  animation: float-02d87c83 3s ease-in-out infinite;
  cursor: pointer;
}

.pet-emoji-container {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
}

.dialog-text {
  font-family: "Comic Sans MS", cursive, sans-serif;
  color: #ff6b81; /* 粉红色 */
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  text-align: center;
  font-size: 14px;
}

.text-jitter {
  padding: 10px 15px;
  max-width: 300px;
  min-width: 200px;
  word-wrap: break-word;
  animation: jitter 0.5s linear infinite;
}

@keyframes jitter {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-2px);
  }
  50% {
    transform: translateX(2px);
  }
  75% {
    transform: translateX(-1px);
  }
}

/* 按钮组样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.cancel-btn {
  background: #ff85a2;
  color: white;
  padding: 8px 25px;
  border-radius: 20px;
  border: none;
  cursor: pointer;
}

.confirm-btn {
  background: none;
  color: #999;
  border: none;
  cursor: pointer;
}

.cancel-btn.hover-animation {
  animation: wiggle 0.5s infinite;
}

@keyframes wiggle {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-3deg);
  }
  50% {
    transform: rotate(3deg);
  }
  75% {
    transform: rotate(-3deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

/* 动画定义 */
@keyframes float {
  0%,
  100% {
    transform: translate(-50%, -50%) translateY(0);
  }
  50% {
    transform: translate(-50%, -50%) translateY(-8px);
  }
}

.shake {
  animation: shake 0.5s linear 2;
}

@keyframes shake {
  0% {
    transform: translate(-50%, -50%) translateX(0);
  }
  25% {
    transform: translate(-50%, -50%) translateX(10px);
  }
  50% {
    transform: translate(-50%, -50%) translateX(-10px);
  }
  75% {
    transform: translate(-50%, -50%) translateX(8px);
  }
  100% {
    transform: translate(-50%, -50%) translateX(0);
  }
}
</style>